package ae.pcfc.etks.online.web.controller.admin.workflow.general.company.request;

/* $Id: NonClientCompanyController.java 
 * Copyright (C) 2011, TRAKHEES
 *  
 * Revision History
 *
 * Date  			Author 		    	Remarks
 * ---------------------------------------------------------------------------------
 * April 11, 2011 	Mohtisham.Salahria	Created
 *
 */

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.UnhandledException;
import org.apache.commons.lang.WordUtils;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.support.RequestContextUtils;

import ae.pcfc.etks.online.common.ConstantsCommon;
import ae.pcfc.etks.online.common.ConstantsCommon.WFProcessType;
import ae.pcfc.etks.online.common.delegate.AdminNonClientCompanyReviewDelegate;
import ae.pcfc.etks.online.common.delegate.AppMetaDataDelegate;
import ae.pcfc.etks.online.common.delegate.UserDelegate;
import ae.pcfc.etks.online.common.util.CommonUtils;
import ae.pcfc.etks.online.common.vo.AdminApprovalVO;
import ae.pcfc.etks.online.common.vo.LabelVO;
import ae.pcfc.etks.online.common.vo.NonClientCompanyVO;
import ae.pcfc.etks.online.common.vo.StepActionVO;
import ae.pcfc.etks.online.common.vo.StepCommentVO;
import ae.pcfc.etks.online.common.vo.WorkFlowTaskInformationVO;
import ae.pcfc.etks.online.web.ConstantsAdmin;
import ae.pcfc.etks.online.web.PageType;
import ae.pcfc.etks.online.web.ViewPath;
import ae.pcfc.etks.online.web.ViewUtils;
import ae.pcfc.etks.online.web.common.Constants;
import ae.pcfc.etks.online.web.controller.BaseController;
import ae.pcfc.etks.online.web.model.NonClientCompanyRegistrationLicenseInfo;
import ae.pcfc.etks.online.web.model.RegisterAdminReview;
import ae.pcfc.etks.online.web.util.SecurityUtils;

/**
 * Controller that handles all {@link AdminReviewController}-related requests,
 * i.e.: all requests for /admin/general/company/request/nonclient/*
 * 
 * @author Mohtisham.Salahria
 */
@Controller
@RequestMapping(ViewPath.ADMIN_GENERAL_COMPANY_REQUEST_NON_CLIENT)
public class AdminNonClientCompanyController extends BaseController {

	private AdminNonClientCompanyReviewDelegate adminNonClientCompanyReviewDelegate;

	@Resource(name = "adminNonClientCompanyReviewDelegate")
	public void setAdminNonClientCompanyReviewDelegate(AdminNonClientCompanyReviewDelegate adminNonClientCompanyReviewDelegate) {
		this.adminNonClientCompanyReviewDelegate = adminNonClientCompanyReviewDelegate;
	}
	
	private UserDelegate userDelegate;
	
	@Resource(name = "userDelegate")
	public void setUserDelegate(UserDelegate userDelegate) {
		this.userDelegate = userDelegate;
	}

	private AppMetaDataDelegate appMetaDataDelegate;

	@Resource(name = "appMetaDataDelegate")
	public void setAppMetaDataDelegate(AppMetaDataDelegate appMetaDataDelegate) {
		this.appMetaDataDelegate = appMetaDataDelegate;
	}

	/**
	 * A factory method for creating or loading an existing company. an optional
	 * parameter specifying the id of the NonClientCompanyVO. If left
	 * unspecified a new NonClientCompanyVO is created.
	 * 
	 * @return an instance of an NonClientCompanyVO model object
	 */

	@ModelAttribute(value = ConstantsAdmin.NON_CLIENT_COMPANY_REGISTRATION_ADMIN_REVIEW_REQUEST_MODEL_KEY)
	public NonClientCompanyVO populateNonClientCompanyData(HttpServletRequest request,
			@RequestParam(value = "appid", required = true) String appid) {

		if (appid != null) {
			NonClientCompanyVO nonClientCompanyVO = adminNonClientCompanyReviewDelegate
					.getNonClientCompanyByApplicationId(SecurityUtils.decrypt(appid));

			if (nonClientCompanyVO!= null)
			{
				return nonClientCompanyVO;
			}
			else{
				throw new UnhandledException("Not Data found for App Id: "+ SecurityUtils.decrypt(appid), null);
			}
		}

		return null;

	}

	@ModelAttribute(value = ConstantsAdmin.ADMIN_ACTION_HISTORY_REQUEST_MODEL_KEY)
	public AdminApprovalVO populateActionHistory(HttpServletRequest request,
			@RequestParam(value = "appid", required = true) String appid) {

		if (appid != null) {
			AdminApprovalVO adminApprovalVO = appMetaDataDelegate.loadAppMetaData(SecurityUtils.decrypt(appid));
			return (adminApprovalVO == null) ? new AdminApprovalVO() : adminApprovalVO;
		}

		// TODO Here we'll place the logic to load the User Data through an Id
		return new AdminApprovalVO();
	}

	/**
	 * Custom handler for displaying the data, i.e.: GET requests for
	 * /admin/general/company/request/nonclient.
	 * 
	 * @see #form(NonClientCompanyRegistrationLicenseInfo)
	 * @see WEB-INF/jsp/admin/general/company/request/nonclient/form.jsp
	 */
	@RequestMapping(value = "/form.htm", method = RequestMethod.GET)
	public void form(
        		HttpServletRequest request,
        		@RequestParam(value = "appid", required = true) String appid,
        		@RequestParam(value = "Incident", required = true) String incident,
        		@RequestParam(value = "StepName", required = true) String stepName,
			@ModelAttribute(value = ConstantsAdmin.REGISTER_ADMIN_REVIEW_REQUEST_MODEL_KEY) RegisterAdminReview adminReview) {

/*		adminReview.setStrApplicationId(appid);
		adminReview.setStrUserName(userName);
		adminReview.setStrTaskId(taskID);
		adminReview.setStrIncidentNo(incident);
		adminReview.setStrStepName(stepName);
		adminReview.setDepartment(UtilCommon.getDepartmentFromStepCode(stepCode));*/
		adminReview.setStrApplicationId(appid);
		String userName = request.getRemoteUser();
		if(!StringUtils.isBlank(userName)){
			userName=WordUtils.capitalize(userName.toLowerCase(),new char[]{'.'});
			// TEMPORARY FIX - Code added to make sure user name is matching with one in Active directory(case sensitive)
		    final String DOT_SEPERATOR = "."; 
		    final String MIDDLE_NAME = "Al";
		    if(StringUtils.startsWith(StringUtils.substringAfter(userName,DOT_SEPERATOR), MIDDLE_NAME))		    		
		    {
		    	String tempLastName = StringUtils.substringAfter(userName,DOT_SEPERATOR);	
		    	tempLastName = MIDDLE_NAME+WordUtils.capitalize(StringUtils.substringAfter(tempLastName,MIDDLE_NAME));
		    	userName = StringUtils.substringBefore(userName,DOT_SEPERATOR)+DOT_SEPERATOR+tempLastName;
		    }
		    // End TEMP FIX
		    adminReview.setStrUserName(CommonUtils.appendDomainPrefix(userName));
		}
		
		//adminReview.setStrUserName(userName);
		//adminReview.setStrTaskId(taskID);
		
		adminReview.setStrIncidentNo(SecurityUtils.decrypt(incident));
		stepName = SecurityUtils.decrypt(stepName);
		adminReview.setStrStepName(stepName);
		// delete 'REVIEW' from 'CED Review' and trim 
		//adminReview.setDepartment(StringUtils.trim(StringUtils.remove(stepName.toUpperCase(), ConstantsCommon.PROCESS_STEP_REVIEW).toUpperCase()));
	}
	@RequestMapping(value = "/show.htm", method = RequestMethod.GET)
	public void show(@RequestParam(value = "appid", required = true) String appid) {
	}

	@ModelAttribute(ConstantsAdmin.NON_CLIENT_PERSON_REGISTER_ACTION_TYPE_LIST_REQUEST_MODEL_KEY)
	public List<LabelVO> populateActionTypeListModel(Locale locale) {

		List<LabelVO> labelList = new ArrayList<LabelVO>();

		LabelVO labelVO = new LabelVO();
		
		labelVO.setId(ConstantsCommon.APPROVE);
		labelVO.setLabelAr(getMessageSource().getMessage("label.admin.approve", null, locale));
		labelVO.setLabelEn(getMessageSource().getMessage("label.admin.approve", null, locale));
		labelList.add(labelVO);

		labelVO = new LabelVO();
		
		labelVO.setId(ConstantsCommon.REJECT);
		labelVO.setLabelAr(getMessageSource().getMessage("label.admin.reject", null, locale));
		labelVO.setLabelEn(getMessageSource().getMessage("label.admin.reject", null, locale));
		labelList.add(labelVO);

		return labelList;
	}
	
	@ModelAttribute(ConstantsAdmin.WORKFLOW_STEPNAME)
	public List<String> getNextStepName(HttpServletRequest request, @RequestParam(value = "Incident", required = true) String incidentNo) {

		return userDelegate.getTaskInformation(Integer.parseInt(SecurityUtils.decrypt(incidentNo)), ConstantsAdmin.PROCESS_CODE_NON_CLIENT_COMPANY_REGISTRATION);
	}
	
	

	/**
	 * Custom handler for displaying the form, i.e.: POST requests for
	 * /admin/general/company/request/nonclient/form.
	 * 
	 * @see #form(HttpServletRequest,SessionStatus,NonClientCompanyRegistrationLicenseInfo,
	 *      BindingResult)
	 * @see WEB-INF/jsp/admin/general/company/request/nonclient/form.jsp
	 */

	@RequestMapping(method = RequestMethod.POST, value = "/form.htm")
	public String form(HttpServletRequest request, HttpSession session, SessionStatus status,
			@ModelAttribute(value = ConstantsAdmin.REGISTER_ADMIN_REVIEW_REQUEST_MODEL_KEY) @Valid RegisterAdminReview adminReview,
			BindingResult errors) {

		AdminApprovalVO adminVO = new AdminApprovalVO();

		getMapper().map(adminReview, adminVO);
		adminVO.setProcessCode(WFProcessType.NON_CLIENT_COMPANY_REGISTRATION);
		//adminVO.setStrProcessStep(adminReview.getStrStepName());
		//adminVO.setStrProcessCode(ConstantsAdmin.PROCESS_CODE_NON_CLIENT_COMPANY_REGISTRATION);
		/*if(adminReview != null && adminReview.getDepartment() != null){
			adminVO.setDepartment(adminReview.getDepartment());
			adminVO.setStrProcessStep(ConstantsAdmin.PROCESS_STEP_REVIEW_NON_CLIENT_COMPANY + ConstantsCommon.PROCESS_STEP_CODE_CONNECTOR + adminReview.getDepartment());
		}else{
			adminVO.setStrProcessStep(ConstantsAdmin.PROCESS_STEP_REVIEW_NON_CLIENT_COMPANY);
		}*/
		adminVO.setStrApplicationId(SecurityUtils.decrypt(adminReview.getStrApplicationId()));
		adminVO.setActionDate(Calendar.getInstance().getTime());

		StepActionVO stepActionVO = new StepActionVO();

		getMapper().map(adminReview, stepActionVO);
		stepActionVO.setActionDate(Calendar.getInstance().getTime());
		
		StepCommentVO stepCommentVO = new StepCommentVO();

		getMapper().map(adminReview, stepCommentVO);
		stepCommentVO.setCommentDate(Calendar.getInstance().getTime());
		
		adminVO.setCommentsVOs(new ArrayList<StepCommentVO>(Arrays.asList(stepCommentVO)));
		adminVO.setStepActionVOs(new ArrayList<StepActionVO>(Arrays.asList(stepActionVO)));
		
		if (adminVO.getStrActionType().equals(ConstantsCommon.APPROVE)) {
			adminVO.setStrStatusEn(getMessageSource().getMessage("msg.workflow.status.approved", null, Locale.ENGLISH));
			adminVO.setStrStatusAr(getMessageSource().getMessage("msg.workflow.status.approved", null, new Locale(Constants.LOCALE_ARABIC)));
		} else if (adminVO.getStrActionType().equals(ConstantsCommon.REJECT)) {
			adminVO.setStrStatusEn(getMessageSource().getMessage("msg.workflow.status.rejected", null, Locale.ENGLISH));
			adminVO.setStrStatusAr(getMessageSource().getMessage("msg.workflow.status.rejected", null, new Locale(Constants.LOCALE_ARABIC)));
		}

		adminVO.setStrInProgressStatusEn(getMessageSource().getMessage("msg.workflow.status.in.progress", null, Locale.ENGLISH));
		adminVO.setStrInProgressStatusAr(getMessageSource().getMessage("msg.workflow.status.in.progress", null, new Locale(Constants.LOCALE_ARABIC)));
		
		adminNonClientCompanyReviewDelegate.reviewNonClientCompany(adminVO, adminReview.getStrUserName());

		if (errors.hasErrors()) {
			return ViewUtils.DEFAULT_VIEW;
		}

		status.setComplete();
		session.setAttribute(ConstantsAdmin.SUCCESS_PARAM,
				getMessageSource().getMessage("label.success.registerservice", null, RequestContextUtils.getLocale(request)));

		return ViewUtils.getRedirect(ViewPath.USER_INTERNAL_TRAKHEES_STAFF_INBOX, PageType.LIST);

	}
}
